/*
 * @Author: Bable znz980@qq.com
 * @Date: 2022-07-13 10:32:27
 * @LastEditors: Bable znz980@qq.com
 * @LastEditTime: 2022-07-26 16:24:44
 * @FilePath: /circulation-web/src/components/EntryPointsContainer.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import * as React from "react";
import EntryPointsTabs from "./EntryPointsTabs";
import { Modal } from "react-bootstrap";
import { CollectionContainerProps } from "opds-web-client/lib/components/Root";
import Collection from "opds-web-client/lib/components/Collection";
// import { CollectionContainerProps } from "../my_modules/opds-web-client/lib/components/Root";
// import MyCollection from "../my_modules/opds-web-client/lib/components/Collection"; //修改为自定义Collection

/** Wrapper for `EntryPointsTabs`. This component is passed into the
    OPDSCatalog from opds-web-client. */
// class MyCollection extends Collection{

// }

// MyCollection.render() = function () {

// }

const applocation_root = localStorage.getItem("MOBEBR_CONFIG_APPLICATION_ROOT");
// console.log("Refresh applocation_root = ", applocation_root);
export default class EntryPointsContainer extends React.Component<
  CollectionContainerProps,
  {
    showModal: boolean; // 是否应显示模态框
    loading: number; // 加载状态
    chooseFile: boolean; // 是否已选择文件
    waiting: boolean; // 上传加载动画状态
    downloading: boolean;
  }
> {
  fileInputRef = React.createRef<HTMLInputElement>();
  constructor(props: CollectionContainerProps) {
    super(props);
    this.fileInputRef = React.createRef();
    this.state = {
      showModal: false,
      loading: 0,
      chooseFile: false,
      waiting: false,
      downloading: false,
    };
  }

  // 上传模版
  handleConfirmUpload = () => {
    if (this.state.chooseFile) {
      console.log("upload_work_excel, now!");
      this.setState({ waiting: true }); // 显示加载中
      const file = this.fileInputRef.current.files[0];
      const formData = new FormData();
      formData.append("file", file);
      const uploadURL = `${applocation_root}/admin/upload_work_excel`;
      fetch(uploadURL, {
        method: "POST",
        body: formData,
      })
        .then((response) => {
          if (!response.ok) {
            throw new Error("Internal Server Error");
          }
          return response.json(); // 将响应解析为JSON
        })
        .then((data) => {
          // 处理JSON响应数据
          console.log(this.state.showModal, "6666");
          this.setState({ waiting: false }, () => {
            // 在 setState 的回调函数中延迟执行弹窗代码
            console.log("Upload response:", data);
            this.setState({ showModal: false });
            if (data.code === "00") {
              // 先关闭模态框
              setTimeout(() => {
                window.alert(`${data.msg}`);
                window.location.reload();
              }, 1000);
              console.log(this.state.showModal, "7777");
            } else {
              setTimeout(() => {
                window.alert(`Upload failed. Error: ${data.msg}`);
              }, 0);
            }
          });
          this.setState({ loading: 1 }); // Show loading
          this.checkExcelProcessingStatus(); // Check Excel processing status
          console.log(this.state.showModal, "9999");
        })
        .catch((error) => {
          // 处理错误
          console.error("Upload error:", error);
          this.setState({ loading: 1 }); // Hide loading
          this.setState({ waiting: false }); // 显示加载中
        })
        .finally(() => {
          // 无论成败，隐藏模态
          this.setState({ showModal: false }); //模态框关闭
          this.setState({ waiting: false }); // 显示加载中
          console.log(this.state.showModal, "0000");
        });
    }
  };

  // 下载模版
  handleDownloadFile = () => {
    this.setState({ downloading: true }); // 显示加载动画
    console.log("Downloading in progress now!");

    const timestamp = Date.now(); // API URL尾部增加动态时间戳，避免被浏览器缓存
    const fileUrl =
      `${applocation_root}/admin/download_work_excel` + `?v=` + timestamp;

    fetch(fileUrl)
      .then((response) => {
        console.log(response);
        if (!response.ok) {
          throw new Error("Network response was not ok");
        }
        return response.blob(); // Get the response as a Blob
      })
      .then((blob) => {
        // Create a temporary URL for the Blob
        const url = window.URL.createObjectURL(blob);
        // Create a link element to trigger the download
        const a = document.createElement("a");
        a.href = url;
        a.download = "Upload_Hidden_Books_Template.xlsx"; // Specify the desired file name
        document.body.appendChild(a);
        a.click();
        // Clean up by revoking the object URL
        window.URL.revokeObjectURL(url);
        this.setState({ downloading: false }); // 出错时也要切换回按钮状态
      })
      .catch((error) => {
        console.error("Error:", error);
        this.setState({ downloading: false });
      });
  };

  // 检查Excel处理状态
  checkExcelProcessingStatus = () => {
    console.log("Check Finish");
    const checkURL = `${applocation_root}/admin/isDownloadExcel`;
    const interval = setInterval(() => {
      fetch(checkURL)
        .then((response) => response.json())
        .then((data) => {
          if (data.status === 200) {
            if (data.message === "It's not ready yet") {
              // 继续等待处理完成
              console.log(this.state.showModal, "1111");
            } else {
              // 处理完成，显示结果
              clearInterval(interval); // 停止定期检查
              this.setState({ loading: 1 }); // 隐藏遮罩
              this.setState({ waiting: false }); // 显示加载中
              this.setState({ downloading: false });
              console.log(this.state.showModal, "2222");
              // 处理后端返回的结果
            }
          } else {
            clearInterval(interval); // 停止定期检查
            this.setState({ loading: 1 }); // 隐藏遮罩
            this.setState({ waiting: false }); // 显示加载中
            this.setState({ downloading: false });
            console.log(this.state.showModal, "3333");
            // 处理错误的情况
          }
        })
        .catch((error) => {
          clearInterval(interval); // 停止定期检查
          this.setState({ loading: 1 }); // 隐藏遮罩
          this.setState({ waiting: false }); // 显示加载中
          this.setState({ downloading: false });
          console.log(this.state.showModal, "4444");
          // 处理错误的情况
        });
    }, 1000); // 每秒钟检查一次，可以根据实际情况调整时间间隔
  };

  // 选择文件
  handleChooseFile = () => {
    this.fileInputRef.current.value = null; // 清空已选择的文件
    this.fileInputRef.current.click();
    console.log("ChooseFile!");
  };

  // 是否已选择文件
  handleFileSelected = () => {
    this.setState({ chooseFile: true }); // 隐藏遮罩
  };

  // 处理上传按钮点击事件，打开模态框
  handleUpload = () => {
    this.setState({ showModal: true });
    this.setState({ loading: 0 }); // 隐藏遮罩
    this.setState({ chooseFile: false });
  };

  // 处理模态框关闭事件
  handleClose = () => {
    this.setState({ showModal: false });
  };

  // 更新上传文件
  handleUpdate = () => {
    this.handleChooseFile();
    console.log("Update completed!");
  };

  // 用于检查文件是否为 xlsx 格式
  isXLSXFile() {
    const file = this.fileInputRef.current.files[0];
    const allowedExtensions = /(\.xlsx)$/i;
    console.log("Verify completed!");
    return allowedExtensions.exec(file.name) !== null;
  }

  render(): JSX.Element {
    const { loading } = this.state;
    const { chooseFile } = this.state;
    const child = React.Children.only(
      this.props.children
    ) as React.ReactElement<any>;
    const collectionCopy = JSON.parse(JSON.stringify(child.props.collection));
    const facetGroups =
      collectionCopy && collectionCopy.facetGroups
        ? collectionCopy.facetGroups
        : [];
    const newProps = Object.assign({}, child.props);

    let facets = [];
    if (facetGroups && facetGroups.length) {
      let remove;
      facetGroups.forEach((facetGroup, i) => {
        if (facetGroup.label === "Formats") {
          remove = i;
          facets = facetGroup.facets.slice();
        }
      });

      // We do not want to display the formats facets in the left sidebar,
      // so remove it from the facetGroups and update it in the new Collection props.
      if (remove !== undefined) {
        facetGroups.splice(remove, 1);
      }
    }

    collectionCopy.facetGroups = facetGroups;
    newProps.collection = collectionCopy;

    const collection = React.createElement(Collection, newProps);
    // const collection = React.createElement(MyCollection, newProps);

    // Check if the URL contains"%2Fadmin%2Fsuppressed"
    const shouldRenderButton = window.location.href.includes(
      "%2Fadmin%2Fsuppressed"
    );

    return (
      <>
        <div className="entry-points-tab-container">
          <EntryPointsTabs facets={facets} />
          <div className="btn-container">
            {shouldRenderButton && (
              <div style={{ display: "flex", justifyContent: "flex-end" }}>
                <div className="collection-button">
                  <button className="btn" onClick={this.handleUpload}>
                    Upload To-Hide Books List
                  </button>
                </div>
              </div>
            )}
            {/* 模态框 */}
            <Modal show={this.state.showModal} onHide={this.handleClose}>
              <Modal.Header closeButton>
                <Modal.Title>Upload To-Hide Books List</Modal.Title>
              </Modal.Header>
              <Modal.Body>
                {/* 模态框的内容 */}
                <>
                  {loading === 0 && (
                    <div>
                      <p>1.Download Template</p>
                      <p>
                        Please download the "Upload_Hidden_Books_Template.xlsx"
                        and fill in
                      </p>
                      <p>the template before uploading</p>
                      {this.state.downloading ? ( // 如果等待状态为true，显示加载动画和文字
                        <button
                          className="btn"
                          style={{ width: "180px", display: "inline" }}
                        >
                          <i className="fa fa-spinner fa-spin" />
                        </button>
                      ) : (
                        <button
                          className="btn"
                          style={{ width: "180px", display: "inline" }}
                          onClick={this.handleDownloadFile}
                        >
                          Download Template
                        </button>
                      )}
                      <p>2.Select File(support xlsx file format only)</p>
                      {!chooseFile && (
                        <button
                          className="btn"
                          style={{ width: "180px", display: "inline" }}
                          onClick={this.handleChooseFile}
                        >
                          {" "}
                          Choose{" "}
                        </button>
                      )}
                      {chooseFile && (
                        <div>
                          {this.fileInputRef.current &&
                            this.fileInputRef.current.files && (
                              <div>
                                {/* Display uploaded file name */}
                                <p>
                                  Selected File:{" "}
                                  {this.fileInputRef.current.files[0].name}
                                </p>
                                {this.isXLSXFile() ? (
                                  <p>
                                    The file is parsed successfully. Click
                                    “Confirm Upload” to import it.
                                    <span
                                      role="img"
                                      aria-label="confirm upload"
                                    >
                                      {" "}
                                      ✅
                                    </span>
                                  </p>
                                ) : (
                                  <p>
                                    Parse error. Please download the template to
                                    fill and upload again.
                                    <span role="img" aria-label="upload error">
                                      {" "}
                                      ❌
                                    </span>
                                  </p>
                                )}
                                <button onClick={this.handleUpdate}>
                                  Update File
                                </button>
                              </div>
                            )}
                        </div>
                      )}
                      <input
                        type="file"
                        ref={this.fileInputRef}
                        style={{ display: "none" }}
                        onChange={this.handleFileSelected}
                      />{" "}
                    </div>
                  )}
                </>
              </Modal.Body>
              <Modal.Footer className="justify-content-end">
                {this.state.waiting ? ( // 如果等待状态为true，显示加载动画和文字
                  <button
                    className="btn"
                    style={{ width: "150px", display: "inline" }}
                  >
                    <i className="fa fa-spinner fa-spin" />
                  </button>
                ) : (
                  <button
                    className="btn"
                    style={{ width: "150px", display: "inline" }}
                    onClick={this.handleConfirmUpload}
                  >
                    Confirm Upload
                  </button>
                )}
              </Modal.Footer>
              <div>{/* 其他组件内容 */}</div>
            </Modal>
          </div>
          {collection}
        </div>
      </>
    );
  }
}
